package com.talkyun.openx.server;

import com.talkyun.openx.RestfulFilter;
import junit.framework.TestCase;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractServletTestCase extends TestCase {
    protected static final Logger logger = LoggerFactory.getLogger(AbstractServletTestCase.class);

    static {
        final Server server = new Server(9099);
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        FilterHolder holder = new FilterHolder(RestfulFilter.class);
        // ServletHolder holder = new ServletHolder(RestfulServlet.class);
        // context.addServlet(holder, "/*");
        context.addFilter(holder, "/*", 0);
        server.setHandler(context);
        try {
            server.start();
            context.start();
            logger.info("Jetty is started. ");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    server.stop();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
}